/**
 * Copyright (C), 2015-2021, 开度
 * FileName: PasswordEncoderUtils
 * Author:   ASUS
 * Date:     2021/8/18 9:50
 * Description: 用户密码加密工具
 * History:
 * <author>          <time>          <version>          <desc>
 * Hezeyu           2021/8/18           1.0              用户密码加密工具
 */
package com.example.spring.security.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 〈用户密码加密工具〉
 *
 * @author Hezeyu
 * @create 2021/8/18
 * @since 1.0.0
 */
@Data
@Slf4j
public class PasswordEncoderUtils {


    private final static Map<Integer, String> ENCODER_TYPE = new HashMap<>();

    private final static Map<String, PasswordEncoder> ENCODER_MAP = new HashMap<>();

    static {
        ENCODER_TYPE.put(0, "bcrypt");
        ENCODER_TYPE.put(1, "pbkdf2");
        ENCODER_TYPE.put(2, "scrypt");
        ENCODER_MAP.put("bcrypt", new BCryptPasswordEncoder());
        ENCODER_MAP.put("pbkdf2", new Pbkdf2PasswordEncoder());
        ENCODER_MAP.put("scrypt", new SCryptPasswordEncoder());
    }

    public static PasswordEncoder init(){
        // 随机使用加密方式
        Random random = new Random();
        int x = random.nextInt(3);
        String encoderType = ENCODER_TYPE.get(x);
        PasswordEncoder passwordEncoder = ENCODER_MAP.get(encoderType);
        return passwordEncoder;
    }
    /**
     *
     * 需要加密，解密的字符
     * @param character 字符串
     * @return:java.lang.String
     * @since: 1.0.0
     * @Author:hezeyu
     * @Date: 2021/8/18 10:00
     * @throws
     */
    public static String encode(String character) throws Exception {
        if(StringUtils.isEmpty(character)){
            throw new Exception("字符串不能为空!");
        }
        PasswordEncoder passwordEncoder = init();
        return passwordEncoder.encode(character);
    }
}
